package com.ys.service.finance.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.entity.finance.*;
import com.ys.entity.hr.ThrOperateCompanyBankInfo;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.finance.PaymentEnum;
import com.ys.enume.finance.TcwWanliPayoutEnum;
import com.ys.enume.wanli.WfSubUserEnum;
import com.ys.mapper.finance.TcwPaymentReturnItemMapper;
import com.ys.mapper.finance.TcwWanliPaymentReturnItemMapper;
import com.ys.mapper.finance.TcwWanliTransferMapper;
import com.ys.service.finance.TcwWanliPaymentReturnService;
import com.ys.service.finance.TcwWanliTransferService;
import com.ys.util.RandomUtil;
import com.ys.util.wanli.WanliUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service("tcwWanliTransferService")
public class TcwWanliTransferServiceImpl implements TcwWanliTransferService {
    private static final Logger logger = LoggerFactory.getLogger(TcwWanliTransferServiceImpl.class);

    @Autowired
    private TcwWanliTransferMapper tcwWanliTransferMapper;

    @Autowired
    private TcwWanliPaymentReturnItemMapper tcwWanliPaymentReturnItemMapper;

    @Autowired
    private TcwWanliTransferService tcwWanliTransferService;

    @Autowired
    private TcwWanliPaymentReturnService tcwWanliPaymentReturnService;

    @Autowired
    private TcwPaymentReturnItemMapper tcwPaymentReturnItemMapper;

    /**
     * 新增预付款退回的付款 未启用 待使用中
     */
    @Override
    public R addPaymentReturnItem(Long wanliPaymentReturnItemId) throws Exception {
        TcwWanliTransfer tcwWanliTransfer = null;
        TcwWanliPaymentReturnItem tcwWanliPaymentReturnItem = null;
        TcwPaymentReturnItem tcwPaymentReturnItem = null;
        boolean flag = false;
        String resultStatus = "";
        String resultMessage = "";
        String resultCode = "";
        try {
            tcwWanliPaymentReturnItem = new TcwWanliPaymentReturnItem().setId(wanliPaymentReturnItemId).queryFirst();
            if (tcwWanliPaymentReturnItem.getStatePay() == PaymentEnum.StatePay.SUCCESS.value) {
                return R.error("该数据已支付,请核实后再操作!");
            }
            tcwWanliPaymentReturnItem.setStatePay(PaymentEnum.StatePay.PROCESS.value);

            //查询主表信息
            TcwWanliPaymentReturn tcwWanliPaymentReturn =  new TcwWanliPaymentReturn().setBid(tcwWanliPaymentReturnItem.getWanliPaymentReturnBid()).queryFirst();

            //查询退回信息
            tcwPaymentReturnItem = new TcwPaymentReturnItem().setId(tcwWanliPaymentReturnItem.getPaymentReturnItemId()).queryFirst();

            //查询运营公司银行账户
            ThrOperateCompanyBankInfo thrOperateCompanyBankInfo  = new ThrOperateCompanyBankInfo().setId(tcwPaymentReturnItem.getCompanyBankId()).queryFirst();

            //查询收款平台信息
            TcwDepositPlatform tcwDepositPlatform = new TcwDepositPlatform().setId(tcwWanliPaymentReturn.getDepositPlatformId()).queryFirst();

            //获取收款平台账号
            TcwDepositPlatformAccount tcwDepositPlatformAccount = new TcwDepositPlatformAccount().setDepositPlatformCode(tcwDepositPlatform.getCode()).setVgsbm(thrOperateCompanyBankInfo.getVgsbm()).queryFirst();

            // 万里汇clientId配置
            TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyTwo("wanli-mid-clientId").queryFirst();

            String content = "";
            JSONObject jsonObject = new JSONObject();
            String guid = RandomUtil.getGUID();
            jsonObject.put("transferRequestId", guid);
            jsonObject.put("businessSceneCode","MULTI_ACCOUNT_TRANSFER");


            JSONObject transferFromDetail = new JSONObject();
            JSONObject transferFromAmount = new JSONObject();
            transferFromAmount.put("currency",tcwWanliPaymentReturn.getCurrencyCode());
            transferFromDetail.put("transferFromAmount",transferFromAmount);

            JSONObject transferFromMethod = new JSONObject();
            transferFromMethod.put("paymentMethodType","BALANCE");
            transferFromMethod.put("customerId",tcwDepositPlatform.getMid());
            transferFromDetail.put("transferFromMethod",transferFromMethod);
            jsonObject.put("transferFromDetail",transferFromDetail);

            JSONObject transferToDetail = new JSONObject();
            JSONObject transferToMethod = new JSONObject();

            transferToMethod.put("paymentMethodType","BALANCE");
            transferToMethod.put("customerId",tcwDepositPlatformAccount.getMid());


            transferToDetail.put("transferToMethod",transferToMethod);

            JSONObject transferToAmount = new JSONObject();
            transferToAmount.put("currency",tcwWanliPaymentReturn.getCurrencyCode());
            //TODO 提示 初始版本无JPY日币 日币不需要*100
            transferToAmount.put("value",tcwWanliPaymentReturnItem.getZfAmount().multiply(new BigDecimal(100)));

            transferToDetail.put("transferToAmount",transferToAmount);


            transferToDetail.put("purposeCode","GDS");
            //必须为true 这样的结汇额度才会转移
            transferToDetail.put("needMigrateMaterial",true);
            //用于接收转账通知的地址，万里汇会使用此地址将转账结果通过notifyTransfer接口发送给集成商。
            transferToDetail.put("transferNotifyUrl",MyConfig.getUrlDomain() + "/api/outer/wfStore/test8");

            jsonObject.put("transferToDetail",transferToDetail);

            content = JSONObject.toJSONString(jsonObject);

            String httpMethod = "POST";
            String clientId = tbStaticConfig.getName();
            String uriWithQueryString = WfSubUserEnum.Type.CREATETRANSFER.value;
            String connectedCustomerId = "";

            // 添加万里汇订单记录

            String transferRequestId;
            {
                String mid = null;
                Integer type = TcwWanliPayoutEnum.Type.TCW_WANLIPAYMENTRETURN.value;
                Long relativeId = wanliPaymentReturnItemId;
                transferRequestId = guid;
                BigDecimal transferFromAmountValue = tcwWanliPaymentReturnItem.getZfAmount();
                String currencyCode = tcwWanliPaymentReturnItem.getThCurrencyCode();
                String transferQuote = String.valueOf(tcwWanliPaymentReturnItem.getExchangeRate());
                String transferNotifyUrl = MyConfig.getUrlDomain() + "/api/outer/wfStore/test8";
                String purposeCode = "GDS";
                Integer state = TcwWanliPayoutEnum.State.PROCESS.value;
                tcwWanliTransfer = TcwWanliTransfer.tcwWanliTransfer(mid, type, relativeId, transferRequestId, tcwDepositPlatform.getMid(),
                        transferFromAmountValue, currencyCode,purposeCode,"true",transferNotifyUrl,transferQuote,
                        tcwDepositPlatformAccount.getMid(),tcwWanliPaymentReturnItem.getZfAmount(),
                        resultCode, resultMessage, resultStatus, state, 1);
                tcwWanliTransferMapper.insert(tcwWanliTransfer);
            }

            String result = WanliUtils.result(content, httpMethod, uriWithQueryString, clientId,connectedCustomerId);

            JSONObject resultJOConsult = JSON.parseObject(result);
            if (resultJOConsult.containsKey("result")) {
                JSONObject resultJO = resultJOConsult.getJSONObject("result");
                logger.error("万里汇支付结果",resultJO);
                if (resultJO.containsKey("resultCode") && resultJO.getString("resultStatus").equals("S")) {
                    flag = true;
                    if (resultJO.getString("resultCode").equals("SUCCESS")) {
                        //SUCCESS转账成功 | PROCESSING转账请求已创建
                        tcwWanliTransferService.changeToSuccess(transferRequestId);
                    }else {
                        //支付中
                        tcwWanliPaymentReturnItem.setStatePay(PaymentEnum.StatePay.PROCESS.value);
                        tcwWanliPaymentReturnItemMapper.update(tcwWanliPaymentReturnItem);

                        //预付款退回
                        tcwPaymentReturnItem.setStatus(PaymentEnum.StatePay.PROCESS.value);
                        tcwPaymentReturnItem.setExecutionTime(new Date());
                        tcwPaymentReturnItemMapper.update(tcwPaymentReturnItem);
                    }
                }else {
                    //失败结果
                    resultStatus = resultJO.get("resultStatus").toString();
                    resultMessage = resultJO.get("resultMessage").toString();
                    resultCode = resultJO.get("resultCode").toString();
                }
            }

        }catch (Exception e){
            logger.error("支付异常,请核实后再操作!",e.getMessage(),e);
        }
        finally {
            if (flag == false) {
                //失败参数
                tcwWanliTransfer.setResultStatus(resultStatus);
                tcwWanliTransfer.setResultMessage(resultMessage);
                tcwWanliTransfer.setResultCode(resultCode);
                tcwWanliTransfer.setState(PaymentEnum.StatePay.FAILED.value);
                tcwWanliTransferMapper.update(tcwWanliTransfer);

                //修改详情支付状态
                tcwWanliPaymentReturnItem.setStatePay(PaymentEnum.StatePay.FAILED.value);
                tcwWanliPaymentReturnItemMapper.update(tcwWanliPaymentReturnItem);

                //预付款退回
                tcwPaymentReturnItem.setStatus(PaymentEnum.StatePay.FAILED.value);
                tcwPaymentReturnItem.setExecutionTime(new Date());
                tcwPaymentReturnItemMapper.update(tcwPaymentReturnItem);
                return R.error("支付异常,请核实后再操作!");
            }
        }
        return R.ok();
    }


    @Override
    @Transactional
    public void changeToSuccess(String transferRequestId) throws Exception {
        if (transferRequestId == null || transferRequestId.length() == 0) {
            return;
        }

        TcwWanliTransfer tcwWanliTransfer = new TcwWanliTransfer().setTransferRequestId(transferRequestId).queryFirst();
        if (tcwWanliTransfer == null) {
            return;
        } else if (tcwWanliTransfer.getState() == TcwWanliPayoutEnum.State.SUCCESS.value) {
            return;
        }

        tcwWanliTransfer.setState(TcwWanliPayoutEnum.State.SUCCESS.value);
        tcwWanliTransferMapper.update(tcwWanliTransfer);

        if (tcwWanliTransfer.getType() == TcwWanliPayoutEnum.Type.TCW_WANLIPAYMENTRETURN.value) {//万里汇预付款退回单
            Long id = tcwWanliTransfer.getRelativeId();
            tcwWanliPaymentReturnService.paySuccess(id);
        }

    }
}
